import socket
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class TCPClient:
    def __init__(self, server_address, server_port):
        """
        初始化 TCP 客户端

        :param server_address: 服务器的 IP 地址
        :param server_port: 服务器的端口号
        """
        self.server_address = server_address
        self.server_port = server_port
        self.client_socket = None

    def connect(self):
        """
        连接到服务器
        """
        try:
            self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.client_socket.connect((self.server_address, self.server_port))
            logging.info(f"成功连接到 {self.server_address}:{self.server_port}")
            return True
        except Exception as e:
            logging.error(f"连接失败: {e}")
            self.client_socket = None
            return False

    def send_data(self, data):
        """
        向服务器发送数据

        :param data: 要发送的数据，类型为字符串
        """
        if self.client_socket:
            try:
                self.client_socket.sendall(data.encode('utf-8'))
                logging.info("数据发送成功")
                return True
            except Exception as e:
                logging.error(f"数据发送失败: {e}")
                return False
        else:
            logging.warning("请先连接到服务器")
            return False

    def inner_receive_data(self, buffer_size=1024):
        """
        从服务器接收数据

        :param buffer_size: 接收数据时的缓冲区大小，默认为 1024 字节
        :return: 接收到的数据，如果发生错误则返回空字符串
        """
        if self.client_socket:
            try:
                data = self.client_socket.recv(buffer_size)
                if data:
                    decoded_data = data.decode('utf-8')
                    logging.info(f"接收到数据: {decoded_data}")
                    return decoded_data
                else:
                    logging.info("服务器已关闭连接")
                    return ""
            except Exception as e:
                logging.error(f"数据接收失败: {e}")
                return ""
        else:
            logging.warning("请先连接到服务器")
            return ""


    def receive_data(self):
        """
        从服务器接收数据，设置超时时间
        """
        if self.client_socket:
            
            try:
                data = self.inner_receive_data()
                return data
            except socket.timeout:
                logging.warning("接收数据超时")
                return ""
            except Exception as e:
                logging.error(f"数据接收失败: {e}")
                return ""
        else:
            logging.warning("请先连接到服务器")
            return ""

    def close(self):
        """
        关闭客户端连接
        """
        if self.client_socket:
            self.client_socket.close()
            self.client_socket = None

            logging.info("连接已关闭")

if __name__ == "__main__":
    client = TCPClient("192.168.110.252",8080)
    client.connect()
    client.send_data("get position")

